"""
用类解析http并发送相应请求
"""
from socket import *
from select import *
import re


class WebServer:
    def __init__(self, host: str = "0.0.0.0", port: int = 8888, html=""):
        """
        网页服务端
        :param host: type:str 服务端ip地址
        :param port: typ:
        :param html: 自己编写的网页所在文件夹的绝对路径
        """
        self.host = host
        self.port = port
        self.html = html
        self.address = (host, port)
        self.sock = self.__create_sock()
        self.dict = {}
        self.ep = epoll()

    def __create_sock(self):
        sock = socket()
        sock.bind(self.address)
        sock.setblocking(False)
        return sock

    def __login_sock(self, sock: socket, event):
        self.ep.register(sock, event)
        self.dict[sock.fileno()] = sock

    def run(self):
        self.__login_sock(self.sock, EPOLLIN)
        self.sock.listen(5)
        print("监听端口：", self.port)
        while True:
            events = self.ep.poll()
            # 确认哪个IO对象准备就绪
            for fd, event in events:
                if self.dict[fd] is self.sock:  # 当监听套接字准备就绪时
                    self.__create_conn()
                else:
                    try:
                        self.handle(fd)
                    except:
                        pass
                    self.ep.unregister(fd)  # 不再关注
                    self.dict[fd].close()
                    del self.dict[fd]

    # 创建conn接收套接字对象
    def __create_conn(self):
        conn, addre = self.sock.accept()
        print("connent from", addre)
        conn.setblocking(False)
        self.__login_sock(conn, EPOLLIN)

    # 接收解析http
    def handle(self, fd):
        # 接收http请求
        data = self.dict[fd].recv(1024).decode()
        print(data)

        # 查找请求内容
        request = re.findall("[A-Z]+\s(/\S*)", data)
        print("请求内容：", request[0])
        self._response(request[0], fd)

    # 组织发送响应
    def _response(self, request: str, fd):
        if request == "/":
            filename = self.html + "/index.html"
        else:
            filename = self.html + request
        print("filename：", filename)

        #判断网页是否存在
        try:
            fr = open(filename, "rb")
        except:
            print("没有找到")
            respon = "HTTP/1.1 404 Not Found\r\n"
            respon += "Content-Type:text/html\r\n"
            respon += "\r\n"
            respon += "Sorry Not Found this web"
            respon = respon.encode()
        else:
            print("找到了")
            respon = "HTTP/1.1 200 OK\r\n"
            respon += "Content-Type:text/html\r\n"
            respon += "\r\n"
            respon = respon.encode() + fr.read()
        finally:
            print("发送")
            self.dict[fd].send(respon)


if __name__ == '__main__':
    web = WebServer()
    web.run()
